程式碼
html部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo List</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Todo List</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="新增待辦事項">
<button type="submit">新增</button>
</form>
<ul id="todo-list"></ul>
<script src="script.js"></script>
</body>
</html>
css部分:
ul {
list-style-type: none;
padding: 0;
}
li {
padding: 10px;
margin: 5px 0;
background-color: #f4f4f4;
display: flex;
justify-content: space-between;
align-items: center;
}
li.completed span {
text-decoration: line-through;
color: gray;
}
.delete-btn {
background-color: red;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}
Javascript部分:
// 選擇元素
const todoForm = document.getElementById("todo-form");
const todoInput = document.getElementById("todo-input");
const todoList = document.getElementById("todo-list");
// 頁面載入時從 localStorage 載入待辦事項
document.addEventListener("DOMContentLoaded", function () {
const savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
savedTodos.forEach(todo => addTodoItem(todo.text, todo.completed));
});
// 新增待辦事項
todoForm.addEventListener("submit", function (event) {
event.preventDefault(); // 防止表單提交
const todoText = todoInput.value.trim();
if (todoText !== "") {
addTodoItem(todoText);
todoInput.value = ""; // 清空輸入框
}
});
// 新增待辦事項到列表並保存至 localStorage
function addTodoItem(text, completed = false) {
const li = document.createElement("li");
const span = document.createElement("span");
span.textContent = text;
li.appendChild(span);
const deleteBtn = document.createElement("button");
deleteBtn.textContent = "刪除";
deleteBtn.classList.add("delete-btn");
li.appendChild(deleteBtn);
// 點擊待辦事項標記為完成
span.addEventListener("click", function () {
li.classList.toggle("completed");
saveTodos();
});
// 刪除待辦事項
deleteBtn.addEventListener("click", function () {
li.remove();
saveTodos();
});
if (completed) {
li.classList.add("completed");
}
todoList.appendChild(li);
saveTodos();
}
// 儲存待辦事項到 localStorage
function saveTodos() {
const todos = [];
document.querySelectorAll("#todo-list li").forEach(li => {
todos.push({
text: li.querySelector("span").textContent,
completed: li.classList.contains("completed")
});
});
localStorage.setItem("todos", JSON.stringify(todos));
}
最終結果
包含了標題、一個輸入框、一個新增鈕
輸入要記錄的待辦事項後按新增
會發現最後面會出現一個紅色的刪除按鈕
按下刪除鈕後可以把那一個待辦事項刪除掉